<?php


namespace gizwits\src;


use gizwits\src\Exception\GizwitsException;

abstract class Init
{

    /**
     * @var array
     */
    protected $data = [];

    /**
     * @var string
     */
    protected $router = '';

    /**
     * @var string
     */
    protected $url = '';

    /**
     * @var array
     */
    protected $config = [];

    public function __construct(array $config = [])
    {
        $this->config = $config;
    }

    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        return $this->data[$name] ?? null;
    }

    public function getFullApi()
    {
        return sprintf('%s%s', Config::API, $this->parseRouter());
    }

    public function getFullQuery()
    {
        return sprintf('%s?%s', $this->getFullApi(), http_build_query($this->data));
    }

    private function parseRouter()
    {
        if (strpos($this->router, '{') !== false) {
            $parent = "/\{(\w*)\}/";
            return preg_replace_callback($parent, function ($matches) {
                return $this->data[$matches[1] ?? ''] ?? '';
            }, $this->router);
        }
        return $this->router;
    }

    public function getRouter()
    {
        return $this->router;
    }

    /**
     * @param array $data
     * @return $this
     */
    public function setData(array $data)
    {
        $this->data = array_merge($this->data, $data);
        return $this;
    }

    public function __call($method, $argv)
    {
        if (strpos($method, '_') === 0) {
            $this->data[substr($method, 1)] = $argv[0];
            return $this;
        }
        throw new GizwitsException("{$method} Not Found!");
    }
}